<template>
  <div class="pointDataWatch">
    <MetaSearchForm @on-search="tableSearch">
      <el-form ref="pointDataWatch_form" :model="searchData" label-width="80px">
        <el-form-item label="采集点位" class="pointDataWatch_searchFromItem">
          <el-select v-model="searchData.pointId" placeholder="请选择设备">
            <el-option
              v-for="item in pointList"
              :key="item.id"
              :label="item.pointName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集时间" class="pointDataWatch_searchFromItem">
          <el-date-picker
            v-model="searchData.dateBetween"
            type="daterange"
            range-separator="-"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
    </MetaSearchForm>
    <MetaPageTable
      ref="pointDataWatchTable"
      class="pointDataWatch_table"
      table-title="数据管理"
      :autoReqFirst="false"
      :needSplit="true"
      :needCheckbox="true"
      :splitDisplayItem="splitDisplayItem"
      :need-checkbox="false"
      :is-auto-req="true"
      :req-url="reqUrl"
      :req-data="searchDataForTable"
      req-method="post"
      :display-item="displayItem"
      :btn-group="btnGroup"
      @btnClick="tableBtnClick"
    />
  </div>
</template>


<script>
import MetaPageTable from '../components/MetaPageTable'
import MetaSearchForm from '../components/MetaSearchForm'
import deepClone from '../utils/deepClone'
import utils from '../utils/utils'
export default {
  name: 'pointDataWatch',
  components: {
    MetaPageTable,
    MetaSearchForm
  },
  data () {
    return {
      searchData : {
        pointId: '',
        dateBetween: []
      },
      searchDataForTable: {},
      reqUrl: process.env.PROGOO_GATE_WATER + "reflectivity/list",
      displayItem: [{
        label: '采集点位',
        prop: 'pointName'
      },
      {
        label: '采集时间',
        prop: 'save_time'
      }],
      btnGroup: [{
        id: 'export',
        title: '导出'
      }],
      rolesList: [],
      companyList: [],
      pointList: [],
      paramsList: [],
      splitDisplayItem: {
        sign: ',',
        label: 'modelName',
        prop: 'modelKey',
        value: 'modelValue',
      }
    }
  },
  mounted() {
    this.getEquipmentList(() => {
      if(this.pointList.length > 0) {
        // this.searchData.pointId = this.pointList[0].id
        //加载记忆的设备
        if(this.$route.meta.remember) {
          let equId = localStorage.getItem('dataCenterEquipmentId')
          if(equId && equId !== '') {
            this.searchData.pointId = equId
          }else {
            this.searchData.pointId = this.pointList[0].id
          }
        }else {
          this.searchData.pointId = this.pointList[0].id
        }

        this.searchData.dateBetween = []
        let nowDay = utils.formatDate('yyyy-MM-dd',new Date())
        this.searchData.dateBetween.push(nowDay)
        this.searchData.dateBetween.push(nowDay)
        this.tableSearch()
      }
    })
  },
  methods: {
    getEquipmentList(callback) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "pointEquipment/getPointPageOfCurrentUser",
        method: "post",
        data: {
          page: 1,
          limit: 999999
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.pointList = res.data.result.content
          callback()
        }else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })
    },
    tableBtnClick(item) {
      if (item.button === 'export') {
        let eName = ''
        for(let i in this.pointList) {
          if(this.searchDataForTable.pointId === this.pointList[i].id) {
            eName = this.pointList[i].pointName
            let start = utils.getStrByUnderlineBefore(this.searchDataForTable.datestart, ' ')
            let end = utils.getStrByUnderlineBefore(this.searchDataForTable.dateend, ' ')
            if(this.searchDataForTable.datestart && this.searchDataForTable.dateend) {
              if(start == end) {
                eName += "(" + start + ")"
              }else {
                eName += "(" + start + " - " + end + ")"
              }
            }
            break
          }
        }

        if(item.rows.length > 0) {
          let excelData = []
          for(let i in item.rows) {
            let excelItem = item.rows[i]

            let keyArr = item.rows[i].modelKey.split(",")
            let valueArr = item.rows[i].modelValue.split(",")
            for(let j in keyArr) {
              excelItem[keyArr[j]] = valueArr[j]
            }
            excelData.push(excelItem)
          }
          this.excelExport(excelData,eName)
        }else {
          let params = {}
          params.datestart = this.searchDataForTable.datestart ? this.searchDataForTable.datestart : ''
          params.dateend = this.searchDataForTable.dateend ? this.searchDataForTable.dateend : ''
          params.pointId = this.searchDataForTable.pointId ? this.searchDataForTable.pointId : ''
          params.page = 1
          params.limit = 99999999

          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "reflectivity/list",
            method: "post",
            data: params
          }).then(res => {
            if (res.data.code === 200) {
              if(res.data.result.content.length > 0) {
                let excelData = []
                for(let i in res.data.result.content) {
                  let excelItem = res.data.result.content[i]

                  let keyArr = res.data.result.content[i].modelKey.split(",")
                  let valueArr = res.data.result.content[i].modelValue.split(",")
                  for(let j in keyArr) {
                    excelItem[keyArr[j]] = valueArr[j]
                  }
                  excelData.push(excelItem)
                }
                this.excelExport(excelData,eName)
              }else {
                this.$notify.error({
                  title: '错误',
                  message: "暂无数据，无法导出"
                });
              }
            }else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              });
            }
          })
        }

      }
    },
    tableSearch() {
      let param = {}
      for(let key in this.searchData ) {
        if(key === 'dateBetween') {
          param.datestart = this.searchData[key] && this.searchData[key].length > 0 ? this.searchData[key][0] + ' 00:00:00' : ''
          param.dateend =  this.searchData[key] && this.searchData[key].length > 0 ? this.searchData[key][1] + ' 23:59:59' : ''
        }else {
          param[key] = this.searchData[key]
        }
      }
      this.searchDataForTable = param
      //设备确认选择后存储后 Ray
      localStorage.setItem("dataCenterEquipmentId", this.searchDataForTable.pointId)
      this.$nextTick(() => {
        this.$refs.pointDataWatchTable.formDataInit(true)
      })
    },
    excelExport(datas,eName) {
      require.ensure([], () => {
        const tHeader = []
        let dHeader = []
        dHeader = datas[0].modelName.split(",")
        tHeader.push('采集点位')
        for(let i in dHeader) {
          tHeader.push(dHeader[i])
        }
        tHeader.push('采集时间')

        const filterVal = []
        let modelKey = []
        modelKey = datas[0].modelKey.split(",")
        filterVal.push('pointName')
        for(let i in modelKey) {
          filterVal.push(modelKey[i])
        }
        filterVal.push('save_time')
        // 数据集
        const list = datas;
        const data = this.formatJson(filterVal, list);
        // excel名称可自定义
        const excelName = eName == '' ? "水质参数报表" : '水质参数_' + eName;
        this.$export_json_to_excel(tHeader, data, excelName);
      });
    },
    //格式化json
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.pointDataWatch{
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .pointDataWatch_table {
    width: 100%;
    overflow-y: unset;
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
  .roleChooseSelect {
    width: 100%;
  }
  .pointDataWatch_searchFromItem {
    float: left;
  }
}
</style>
